package com.bangdao.app.jetpacktest.jetpack.livedata;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @ProjectName: JetpackTest
 * @ClassName: TimerWithLiveDataViewModel
 * @Description: java类作用描述
 * @Author: luhui
 * @Email: hui.lu@bangdao-tech.com
 * @CreateDate: 2022/6/4 00:04
 * @UpdateUser: luhui
 * @UpdateDate: 2022/6/4 00:04
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class TimerWithLiveDataViewModel extends ViewModel {
    //将currentSecond这个字段用MutableLiveData包装起来
    private MutableLiveData<Integer> currentSecond;
    private Timer timer;

    public LiveData<Integer> getCurrentSecond(){
        if(currentSecond == null){
            currentSecond = new MutableLiveData<>();
        }
        return currentSecond;
    }

    /**
     * 开始计时
     */
    public void startTiming(){
        if(timer == null){
            currentSecond.setValue(0);//setValue用在UI线程
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    currentSecond.postValue(currentSecond.getValue()+1);//postValue用在UI线程
                }
            };
            timer.schedule(timerTask, 1000, 1000);
        }
    }
}
